﻿using CK.Sprite.Form.Core;
using CK.Sprite.Framework;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CK.Sprite.Form.Business
{
    public class InStockDomainService : DomainService, IBusinessExec
    {
        public SpriteObjectLocalCache _spriteObjectLocalCache => LazyGetRequiredService(ref spriteObjectLocalCache);
        private SpriteObjectLocalCache spriteObjectLocalCache;

        // 参数信息{applicationCode,tenantCode,Params}
        public async Task<JObject> ExecBusinessMethod(JObject execParams, IUnitOfWork unitOfWork = null)
        {
            var applicationCode = execParams["applicationCode"].ToString();
            var tenantCode = execParams["tenantCode"].ToString();
            var arrivalNo = string.Empty;
            if(execParams["params"] != null)
            {
                if (execParams["params"]["paramValues"]["arrivalNo"] != null)
                {
                    arrivalNo = execParams["params"]["paramValues"]["arrivalNo"].ToString();
                }
            }
              
            if (unitOfWork == null)
            {
                var businessConfig = await TenantConfigStore.FindAsync(applicationCode, tenantCode);
                await _serviceProvider.DoDapperServiceAsync(businessConfig, async (unitOfWorkNew) =>
                {
                    var inStockRepository = ConnectionFactory.GetConnectionProvider(BusinessConsts.BusinessConnProviderKey).GetRepository<IInStockRepository>(unitOfWorkNew);
                    await DoExecBusinessMethod(inStockRepository, arrivalNo, applicationCode);
                });
            }
            else
            {
                var inStockRepository = ConnectionFactory.GetConnectionProvider(BusinessConsts.BusinessConnProviderKey).GetRepository<IInStockRepository>(unitOfWork);
                await DoExecBusinessMethod(inStockRepository, arrivalNo, applicationCode);
            }

            return new JObject();
        }

        private async Task DoExecBusinessMethod(IInStockRepository inStockRepository, string arrivalNo,  string applicationCode)
        {
               await inStockRepository.AuditArrivalAsync(arrivalNo);
        }

    }
}
